package czk.concrent.dsisorder;

/**
 * 指令 重排序的复现
 *
 * @Author:ChenZhangKun
 * @Date: 2022/8/29 11:04
 */
public class T01_DisOrder {
    /**
     * volatile lock指令
     * 1  lock用于多处理器中执行指令时对共享内存的独占使用
     * 2 将当前处理器对应的缓存的内容刷新到内存，并使其他处理器对应的缓存失效
     * 3 提供有序指令无法跨越这个内存屏障的作用
     */
    private volatile static int x = 0, y = 0;
    private volatile static int a = 0, b = 0;

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        for (; ; ) {
            i++;
            x = 0;
            y = 0;
            a = 0;
            b = 0;
            Thread one = new Thread(() -> {
                a = 1;
                x = b;
            });
            Thread other = new Thread(() -> {
                b = 1;
                y = a;
            });
            one.start();
            other.start();
            one.join();
            other.join();
            String result = "第" + i + "次(" + x + "," + y + ")";
            if (x == 0 && y == 0) {
                System.err.println(result);
                break;
            } else {

            }
        }
    }
}
